#include <WiFi.h>
#include <PubSubClient.h>

// WiFi 网络配置
const char* ssid = "洛克王国国王专用网络";
const char* password = "123456790";

// MQTT Broker 配置
const char* mqtt_server = "broker.emqx.io";
const int mqtt_port = 1883;

// 按键配置
const int buttonPin = 2;
int buttonState = 0;
int lastButtonState = 0;

// 自我介绍消息
const char* introduction = "Hello, I am PengRuikang from AIAgriculture!";

// 创建WiFi和MQTT客户端实例
WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  // 初始化串口通信
  Serial.begin(115200);
  
  // 设置按键引脚为输入模式
  pinMode(buttonPin, INPUT_PULLUP);
  
  // 连接到WiFi网络
  setup_wifi();
  
  // 设置MQTT服务器和回调函数
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {
  // 检查MQTT连接状态
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  
  // 读取按键状态
  buttonState = digitalRead(buttonPin);
  
  // 检测按键按下事件
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      // 发送自我介绍消息
      client.publish("emqx/AIAgriculture", introduction);
      Serial.println("Introduction sent!");
    }
    delay(50); // 防抖动
  }
  lastButtonState = buttonState;
}

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // 循环直到连接成功
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // 尝试连接
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  // 处理接收到的消息
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (unsigned int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}